/*
 * DA1.asm
 *
 *  Created: 2/13/2015 2:02:09 PM
 *   Author: David Hunt
 */ 


 ldi r16,HIGH(RAMEND)	;Initialize Stack
 out sph, r16
 ldi r16,LOW(RAMEND)
 out spl, r16

 ldi r16, 0				;Set r16 as count
 ldi r17, 24			;Set r17 as 25 for end of count
 ldi r18, 2				;helper to make numbers seemingly random
 ldi r19, 3				;number to be stored on stack				

storeNumbers:			;loop to add up and store numbers on stack
 add r19, r18			;add r18 to r19
 push r19				;push r19 onto stack
 inc r16				;increment r16
 cp r17, r16			;compare r17 to r16
 brge storeNumbers		;continue loop if 24>=r16

 ldi r21, 0				;accumulator for divisible by 7
 ldi r22, 0				;accumulator for divisible by 3

ldANDcmp:
 pop r19				;pop number from stack
 mov r18, r19			;copy number
 ldi r23, 7				;load divisor 7

DIV:
 ldi r24, 9		        ;load bit counter
 sub r25, r25		    ;clear remainder and carry
 mov r26, r19			;copy number to answer
 
LOOP:
 rol r26				;shift the answer to the left
 dec r24					;decrement counter
 breq DD				;exit if eight bits done
 rol r25				;shift the remainder to the left
 sub r25, r23			;try to subtract divisor from remainder
 brcc SKIP				;if the result was negative then
 add r25, r23			;reverse the subtraction to try again
 clc					;clear carry flag so zero shifted into r19 
 rjmp LOOP				;loop back

SKIP:   
 sec		            ;set carry flag to be shifted into r19
 rjmp LOOP				;repeat
DD:

 cpi r25, 0				;compare remainder to zero
 brne DONE7				;jump to DONE7 if not equal, else

 cpi r23, 7				;compare divisor to 7
 brne MOD3				;jump to MOD3 if not equal, else
 add r21, r18			;add popped number to 7's accumulator
 rjmp DONE7				;jump to end DONE7

MOD3:
 add r22, r18			;add popped number to 3's accumulator
 rjmp DONE				;jump to DONE

DONE7: 
 cpi r23, 3				;compare divisor to 3
 breq DONE				;jump to DONE if 3, else
 ldi r23, 3				;set divisor to 3
 rjmp DIV				;redo division with 3 as divisor

DONE:
 dec r16				;decrement counter
 cpi r16, 0				;compare to zero
 brne ldANDcmp			;repeat until all numbers on stack are processed
 nop					;end of program